<?php
namespace App\Service\ApiQd;

use Illuminate\Support\Facades\DB;

class CartService extends BaseService
{
    //购物车

    /**
     * 列表，同商品不过滤
     * @param array $pages【start，limit】
     * @param int $uid
     * @return array
     */
    public function getList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbDistributorCart)
            ->where('del', 0)
            ->where('isorder', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        $qdOne = (array) $this->dbwbConn($this->dbQdShop)->where('id', $uid)->first();
        if (empty($qdOne)) {
            return $this->toback(-2, '没有用户');
        }
        $level = $qdOne['level'];
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //商品信息
            $gname = '-';
            $gimg = '';
            $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
                ->where('id', $v['gid'])->first();
            if (!empty($gOne)) {
                $gname = $gOne['title'];
                $gimg = env('DOMAIN') . '/' . $gOne['bigimg'];
            }
            //SKU信息
            $sku_name = '-';
            $sku_price = 0;
            $sku_price_line = 0;
            $sku_sale = 0;
            $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)
                ->where('id', $v['sku_id'])->first();
            if (!empty($skuOne)) {
                $sku_name = $skuOne['title'];
                $sku_price = $level==1 ? $skuOne['price_one'] : $skuOne['price_two'];
                $sku_price_line = $skuOne['price'];
                $sku_sale = $skuOne['sale'];
            }
            $arys[] = [
                'id' => $v['id'],
                'gid' => $v['gid'],
                'gname' => $gname,
                'gimg' => $gimg,
                'sku_id' => $v['sku_id'],
                'sku_name' => $sku_name,
                'sku_price' => toNumber($sku_price),
                'sku_price_line' => toNumber($sku_price_line),
                'sku_sale' => $sku_sale,
                'num' => $v['num'],
                'gdel' => $v['g_del'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 加入购物车
     * @param int $uid
     * @param int $skuid
     * @param array $pas【shop_id，num，delivery】
     */
    public function add($uid, $skuid, $pas)
    {
        //用户信息
        $uOne = (array) $this->dbwbConn($this->dbDistributorUser)
            ->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        if (!in_array($uOne['level'], [1, 2])){
            return array('code' => -2, 'msg' => '用户级别未设置');
        }
        //SKU信息
        $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)
            ->where('id', $skuid)->first();
        if (empty($skuOne)) {
            return array('code' => -2, 'msg' => '不存在');
        }
        if (!$skuOne['stock']) {
            return array('code' => -2, 'msg' => '库存不足');
        }
        //商品信息
        $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
            ->where('id', $skuOne['gid'])->first();
        if (empty($gOne)) {
            return array('code' => -2, 'msg' => '商品不存在');
        }
        //购物车信息
        $cartOne = (array) $this->dbwbConn($this->dbDistributorCart)
            ->where('del', 0)
            ->where('isorder', 0)
            ->where('uid', $uid)
            ->where('gid', $skuOne['gid'])
            ->where('sku_id', $skuid)
            ->first();
        if (!empty($cartOne) && $cartOne['num'] + 1 > $skuOne['stock']) {
            return array('code' => -2, 'msg' => '商品库存不足');
        }
        DB::beginTransaction(); //开启事务
        try {
            if($uOne['level'] == 1) {
                $price = $skuOne['price_one'];
            }elseif ($uOne['level'] == 2) {
                $price = $skuOne['price_two'];
            }
            //购物车更新
            if (empty($cartOne)) {
                //没有则添加
                $cartData = [
                    'uid' => $uid,
                    'gid' => $skuOne['gid'],
                    'sku_id' => $skuid,
                    'uname' => $uOne['nickname'],
                    'cartno' => toCartno(),
                    'gname' => $gOne['title'],
                    'sku_name' => $skuOne['title'],
                    'gimg' => $gOne['bigimg'],
                    'price' => $price,
                    'num' => $pas['num'],
                    'addtime' => toDate(),
                ];
                $cartUp = $this->dbwbConn($this->dbDistributorCart)->insertGetId($cartData);
                if (!$cartUp) {
                    return array('code' => -2, 'msg' => '购物车添加失败');
                }
            } else {
                //有则递增
                $cartData = [
                    'num' => $pas['num'] + $cartOne['num'],
                    'uptime' => toDate(),
                ];
                $cartUp = $this->dbwbConn($this->dbDistributorCart)->where('id', $cartOne['id'])->update($cartData);
                if (!$cartUp) {
                    return array('code' => -2, 'msg' => '购物车增加失败');
                }
            }
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    /**
     * 递减
     * @param int $uid
     * @param int $id 购物车ID
     * @param array $pas【num，sku_id】
     */
    public function reduce($uid, $id, $pas)
    {
        //用户信息
        $uOne = (array) $this->dbwbConn($this->dbDistributorUser)
            ->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        //购物车信息
        $res = (array) $this->dbwbConn($this->dbDistributorCart)
            ->where('del', 0)
            ->where('isorder', 0)
            ->where('uid', $uOne['id'])
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '购物车空的');
        }
        $pas['uptime'] = toDate();
        $up = $this->dbwbConn($this->dbDistributorCart)
            ->where('id', $id)
            ->update($pas);
        if (!$up) {
            return array('code' => -2, 'msg' => '减少失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 批量删除
     * @param int $uid
     * @param array $cartids 购物车ID集合
     */
    public function batchDel($uid, $cartids)
    {
        //购物车信息
        $res = $this->dbwbConn($this->dbDistributorCart)
            ->where('del', 0)
            ->where('isorder', 0)
            ->where('uid', $uid)
            ->whereIn('id', $cartids)
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '购物车空的');
        }
        $up = $this->dbwbConn($this->dbDistributorCart)
            ->whereIn('id', $cartids)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return array('code' => -2, 'msg' => '删除失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    //根据商品，批量删除
    public function delByGid()
    {
        $gOnes = $this->dbwbConn($this->dbDistributorGoods)->where('del', 1)->get();
        if (empty($gOnes)) {
            return false;
        }
        foreach ($gOnes as $v) {
            $v = (array) $v;
            $this->dbwbConn($this->dbDistributorCart)->where('gid', $v['id'])->update(['g_del' => 1]);
        }
        return true;
    }
}